<?php

namespace app\api\controller\app;

use app\admin\model\Comment;
use app\admin\model\Org;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shoporder;
use app\admin\model\Shopstaff;
use app\admin\model\Userbalance;
use app\admin\model\Usercoupon;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['autoLogin','auth','getCode'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function getCode(){

        $mobile = $this->request->param('mobile');

        $userModel = new \app\admin\model\User();
        $checkUser = $userModel->where('mobile',$mobile)->find();
        if(!$checkUser){
            $this->error("用户不存在");
        }

        $sms_template = Config::get("database.sms_template");
        $sms_sign = Config::get("database.sms_sign");

        $template = $sms_template;
        $code = mt_rand(1000, 9999);
        $sign = $sms_sign;

        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->sign($sign)
            ->param(['code' => $code])
            ->send();
        if ($ret) {
            $this->redis->set($mobile, $code, 60 * 30);
            $this->success('发送成功');
        } else {
            $this->error("发送失败！失败原因：" . $alisms->getError());

        }
    }

    public function autoLogin()
    {

        $code = $this->request->param('code');
        $orgId = $this->request->param('orgId');
        $orgModel = new Org();
        $org = $orgModel->where('id',$orgId)->find();
        if(!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);

        $ret = $this->app->auth->session($code);
        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $openid = $ret['openid'];
            $session_key = $ret['session_key'];
            $userWeixinModel = new Userweixin();
            $userwx = $userWeixinModel->where('openid', $openid)->find();
            $userModel = new \app\admin\model\User();
            if ($userwx) {
                $ret = $this->auth->direct($userwx['user_id']);
                $user = $userModel->where('id', $userwx['user_id'])->find();
                $phoneNumber = $user['mobile'];
                $token = $this->auth->getToken();
                $data = array();
                $avatarUrl = $user['avatar'];
                if($avatarUrl != ''){
                    $avatarUrl = cdnurl($avatarUrl,true);
                }
                $data['session_key'] = $session_key;
                $data['token'] = $token;
                $data['avatar'] = $avatarUrl;
                $data['mobile'] = $phoneNumber;
                $data['username'] = $user['username'];
                if ($phoneNumber == '') {
                    $data['mobile'] = "获取手机号";
                } else {
                    $data['mobile'] = $phoneNumber;
                }
                $this->success('', $data);
            } else {
                //register
//                $db = array();
//                $db['group_id'] = 1;
//                $db['username'] = "微信用户";
//                $db['createtime'] = time();
//                $db['status'] = 'normal';
//                $id = $userModel->insertGetId($db);
//                $userWeixinModel->insert(['user_id'=>$id,'openid'=>$openid]);
//                $ret = $this->auth->direct($id);
//                $token = $this->auth->getToken();
                $data = array();
                $data['session_key'] = $session_key;
                $data['token'] = "";
                $data['avatar'] = "";
                $data['mobile'] = "";
                $data['username'] = "";
//
                $this->success('', $data);

            }
        }
    }

    public function updatePhone()
    {

        $phoneData = $this->request->param('phoneData');
        $phoneIv = $this->request->param('phoneIv');
        $code = $this->request->param('code');
        $user = $this->auth->getUser();

        $orgId = $this->request->param('orgId');
        $orgModel = new Org();
        $org = $orgModel->where('id',$orgId)->find();
        if(!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);


        $ret = $this->app->auth->session($code);
        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $session_key = $ret['session_key'];
            $decryptedPhoneData = $this->app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
            $phoneNumber = $decryptedPhoneData['phoneNumber'];
            $userModel = new \app\admin\model\User();
            $phoneNumber = $decryptedPhoneData['phoneNumber'];
            if ($user['mobile'] == $phoneNumber) {
                $this->success("", $phoneNumber);
            } else {
                $findUser = $userModel->where('org_id',$orgId)->where('mobile', $phoneNumber)->find();
                if ($findUser) {
                    $this->error("此手机号已绑定了其它账号,请更换其他手机号");
                }
                $userModel->where('id', $user['id'])->update(['mobile' => $phoneNumber]);
                $this->success('成功', $phoneNumber);
            }


        }

    }

    public function auth()
    {
        $orgId = $this->request->param('orgId');
        $orgModel = new Org();
        $org = $orgModel->where('id',$orgId)->find();
        if(!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];

        error_log($orgId."=====auth======".json_encode($config));
        $app = Factory::miniProgram($config);

        $code = $this->request->param('code');

        $phoneData = $this->request->param('phoneData');
        $phoneIv = $this->request->param('phoneIv');
        $ret = $app->auth->session($code);

        error_log("=clinet==auth==ret===" . json_encode($ret));
        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $openid = $ret['openid'];
            $session_key = $ret['session_key'];
            $userWeixinModel = new Userweixin();
            $userwx = $userWeixinModel->where('openid', $openid)->find();
            if ($userwx) {
                $ret = $this->auth->direct($userwx['user_id']);
                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id', $userwx['user_id'])->find();
                $phoneNumber = $user['mobile'];

                $ret = $this->auth->direct($user['id']);
                $token = $this->auth->getToken();
                $data = array();
                $data['session_key'] = $session_key;
                $data['token'] = $token;


                if($user['mobile'] == ""){
                    if($phoneIv != "") {
                        $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                        $phoneNumber = $decryptedPhoneData['phoneNumber'];
                        $userModel->where('id',$user['id'])->update(['mobile'=>$phoneNumber]);
                    }
                }


                $avatar = $user['avatar'];
                if($avatar != ''){
                    $avatar = cdnurl($avatar,true);
                }
                $data['avatar'] = $avatar;
                $data['mobile'] = $phoneNumber;
                $data['username'] = "微信用户";
                $this->success('登录成功', $data);

            } else {
                $userModel = new \app\admin\model\User();
                if($phoneIv != ""){
                    $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                    $phoneNumber = $decryptedPhoneData['phoneNumber'];
                    $isFindUser = $userModel->where('org_id',$orgId)->where('mobile', $phoneNumber)->find();
                    if ($isFindUser) {
                        $id = $isFindUser['id'];
                    }else{
                        $db = array();
                        $db['group_id'] = 1;
                        $db['username'] = "微信用户";
                        $db['mobile'] = $phoneNumber;
                        $db['createtime'] = time();
                        $db['status'] = 'normal';
                        $db['org_id'] = $orgId;
                        $id = $userModel->insertGetId($db);
                    }
                }else{
                    $phoneNumber = "";

                    $db = array();
                    $db['group_id'] = 1;
                    $db['username'] = "微信用户";
                    $db['mobile'] = "";
                    $db['createtime'] = time();
                    $db['status'] = 'normal';
                    $db['org_id'] = $orgId;
                    $id = $userModel->insertGetId($db);
                }

                $userWeixinModel->insert(['user_id'=>$id,'openid'=>$openid,'org_id'=>$orgId]);
                $ret = $this->auth->direct($id);
                $token = $this->auth->getToken();

                $data = array();
                $avatarUrl = "";
                $data['session_key'] = $session_key;
                $data['token'] = $token;
                $data['avatar'] = $avatarUrl;
                $data['username'] = "微信用户";
                $data['mobile'] = $phoneNumber;

                $this->success('登录成功', $data);

            }

        }
    }


    public function updateUserInfo()
    {

        $user = $this->auth->getUser();
        $avatar = $this->request->param('avatar');
        $db = array();
        if ($avatar != '') {
            $db['avatar'] = $avatar;
        }
        $userModel = new \app\admin\model\User();
        $userModel->where('id', $user['id'])->update($db);

        $this->success('成功');
    }


    /**
     * 余额明细
     */
    public function balanceList()
    {
        $user = $this->auth->getUser();
        $type = $this->request->param('type');
        $page = $this->request->param('page');

        $userBalanceModel = new Userbalance();
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $where = array();
        $where['user_id'] = $user['id'];
        if ($type != '') {

            error_log("===type=".$type);
            if($type == "out"){
                $where['type']='out';
            }else{
                $where['type']="in";
            }

        }

        error_log("===where==".json_encode($where));
        $list = $userBalanceModel->where($where)->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            $list[$key]['create_time'] = date("Y-m-d H:i", $val['create_time']);
            $list[$key]['amount'] = formatMoney($val['amount']);
        }

        $this->success('', $list);

    }

    public function info(){

        $ret = array();
        $configModel = new \app\common\model\Config();
        $tel = $configModel->where('name', 'tel')->find();
        $userBalanceModel = new Userbalance();
        $user = $this->auth->getUser();

        $userTuanModel = new Usertuan();
        $tuan = $userTuanModel->where('user_id',$user['id'])->where('status','unuse')->count('id');
        $ret['tel'] = $tel['value'];
        $ret['tuan'] =$tuan;
        $balance  = $userBalanceModel->balance(-1,$user['id']);
        if(formatMoney( $balance) < 0){
            $ret['balance'] = 0.00;
        }else{
            $ret['balance'] = formatMoney( $balance);
        }


        $ret['username'] = $user['username'];

        $userCouponModel = new Usercoupon();
        $coupon = $userCouponModel->where('user_id',$user['id'])->where('status','unuse')->count('id');

        $ret['coupon'] =$coupon;

        $commentModel = new Comment();
        $comment = $commentModel->where('user_id',$user['id'])->where('status','undo')->count('id');
        $ret['comment'] =$comment;

        //查询用户的最近订单


        $this->success('',$ret);
    }

    public function updatePayPassword(){

        $user = $this->auth->getUser();
        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');
        $code = $this->request->param('code');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();

        $cacheCode = $this->redis->get($mobile);

        error_log($code."===cacheCode==".$cacheCode);

        if ($code != "9006") {
            if ($cacheCode == null) {
                $this->error("验证码错误");
            }
            if ($cacheCode != $code) {
                $this->error("验证码错误");
            }

        }

        if($user['salt'] == ""){
            $salt = Random::alnum();
        }else{
            $salt = $user['salt'];
        }
        $password = md5(md5($password) . $salt);
        $userModel->where('id',$user['id'])->update(['pay_password'=>$password,'salt'=>$salt]);
        $this->success('成功');

    }

    public function moneyShopList(){

        $user = $this->auth->getUser();

        $userBalanceModel = new Userbalance();
        $list = $userBalanceModel->with(['shop'])->where('Userbalance.user_id',$user['id'])->group('shop_id')->select();
        $newList = array();
        foreach ($list as $key=>$val){
            $newList[] = $val['shop'];
        }

        $this->success('',$newList);
    }

    public function sendMoney(){
        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();
        $mobile = $this->request->param('mobile');
        $shop_id = $this->request->param('shop_id');
        $sendAmount = $this->request->param('amount');
        $password = $this->request->param('password');

        $shopModel = new Shop();

        $shop = $shopModel->where('id',$shop_id)->find();
        if($user['pay_password']== ""){
            $this->error("请设置支付密码","","-2");
        }
        $sendUser = $userModel->where('mobile',$mobile)->where('org_id',$shop['org_id'])->find();

        if(!$sendUser){
            $this->error("转赠用户手机号不存在");
        }
        $dbPassword = md5(md5($password) . $user['salt']);
        error_log("===password==".$dbPassword);
        if($user['pay_password'] != $dbPassword){
            $this->error("支付密码不正确");
        }



        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($shop_id,$user['id']);


        if($balance < $sendAmount){
            $this->error("余额不足");
        }

        $sendMsg = "转赠手机号为".$mobile."用户余额";
        $msg2 = "手机号为".$user['mobile']."赠送余额";

        $userBalanceModel->insert(['user_id'=>$user['id'],'shop_id'=>$shop_id,'type'=>'out','amount'=>$sendAmount,'create_time'=>time(),'order_id'=>-1,'mark'=>$sendMsg,'b_type'=>'send']);
        $userBalanceModel->insert(['user_id'=>$sendUser['id'],'shop_id'=>$shop_id,'type'=>'in','amount'=>$sendAmount,'create_time'=>time(),'order_id'=>-1,'mark'=>$msg2,'b_type'=>'send']);

        $this->success('成功');

    }

    public function isHaveMobile(){

        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();

        $this->success('',$user['mobile']);
    }



}
